﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Configuration;
using System.Web.Security;
using BLToolkit.Data;
using BLToolkit.Data.Linq;
using Calendar.Logic.Log;
using Calendar.Logic.ObjectModel.Authorization;

namespace Calendar.Logic.Core
{
    /// <summary>
    /// Singleton Класс обеспечивающий хранение переменных текущего сеанса
    /// </summary>
    public sealed class GlobalContext : IDisposable
    {
        private static readonly GlobalContext _instance = new GlobalContext();
        private static readonly Dictionary<DateTime, DbManager> DataContexts = new Dictionary<DateTime, DbManager>();
        //private readonly DbManager _dbManager;

        // private constructor
        private GlobalContext()
        {
            DbManager.AddDataProvider(new PostgreSQLDataProvider());

            //_dbManager = new DbManager();
            //_dbManager.AfterOperation += (s, e) =>  LogManager.Log(DsLogLevel.DEBUG, "Запроса к БД", _dbManager.LastQuery);
            //_dbManager.OperationException += (s, e) => LogManager.Log(DsLogLevel.ERROR, "Ошибка при выполнении запроса к БД", e.Exception.Message);

            LogManager.MaxLogLevel = WebConfigurationManager.AppSettings["LogLevelDebug"] == null || WebConfigurationManager.AppSettings["LogLevelDebug"] != "false" ? DsLogLevel.DEBUG : DsLogLevel.ERROR;
            
            ApplicationName = Roles.ApplicationName;
        }

        public void Init()
        {
            foreach (AppRole role in Enum.GetValues(typeof(AppRole)))
            {
                if (!Roles.RoleExists(role.ToString())) Roles.CreateRole(role.ToString());
            }

            if (Membership.Provider.GetUser("root", false) == null)
            {
                MembershipCreateStatus s;
                Membership.Provider.CreateUser("root", "1234567", "root@Calendar.ru", "", "", true, 0, out s);
            }

            if (!Roles.IsUserInRole("root", AppRole.Администратор.ToString()))
            {
                Roles.AddUserToRole("root", AppRole.Администратор.ToString());
            }
        }

        public static GlobalContext Instance
        {
            get { return _instance; }
        }

        public IDataContext DataContext
        {
            get
            {
                if (HttpContext.Current == null) 
                    return new DataContext();

                if (!DataContexts.ContainsKey(HttpContext.Current.Timestamp))
                {
                    DataContexts[HttpContext.Current.Timestamp] = new DbManager();
                }
                return DataContexts[HttpContext.Current.Timestamp];
            }
        }

        public void DelDataContext()
        {
            if (DataContexts.ContainsKey(HttpContext.Current.Timestamp))
            {
                DataContexts[HttpContext.Current.Timestamp].Close();
                DataContexts[HttpContext.Current.Timestamp].Dispose();
                DataContexts.Remove(HttpContext.Current.Timestamp);
            }
        }

        public string ApplicationName { get; set; }

        public void Dispose()
        {
            LogManager.ShutDown();
        }
    }
}
